package com.loong.system.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import com.loong.framework.dto.IdParamDTO;
import com.loong.framework.utils.CommonUtil;
import com.loong.framework.utils.SystemUtil;
import com.loong.system.dto.MenuAddDTO;
import com.loong.system.dto.MenuQueryDTO;
import com.loong.system.dto.MenuUpdateDTO;
import com.loong.system.dto.PermissionAssignmentDTO;
import com.loong.system.entity.Menu;
import com.loong.system.service.IMenuService;
import com.loong.system.vo.MenuDetailVO;
import com.loong.system.vo.MenuVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "菜单操作 API")
@RestController
@RequestMapping("/api/v1.0/menu")
public class MenuController {

  @Resource private IMenuService menuService;

  @SaCheckRole("root")
  @Operation(summary = "新增")
  @PostMapping("/add")
  public void add(@RequestBody @Valid MenuAddDTO addDTO) {
    menuService.addMenu(addDTO);
  }

  @SaCheckRole("root")
  @Operation(summary = "删除")
  @PostMapping("/remove")
  public void remove(@RequestBody @Valid IdParamDTO idParamDTO) {
    menuService.removeMenu(idParamDTO.getId());
  }

  @SaCheckRole("root")
  @Operation(summary = "更新")
  @PostMapping("/update")
  public void update(@RequestBody @Valid MenuUpdateDTO updateDTO) {
    menuService.updateMenu(updateDTO);
  }

  @SaCheckRole("root")
  @Operation(summary = "详情")
  @PostMapping("/detail")
  public MenuDetailVO detail(@RequestBody @Valid IdParamDTO idParamDTO) {
    Menu menu = menuService.getById(idParamDTO.getId());
    return SystemUtil.buildResource(menu, MenuDetailVO.class);
  }

  @SaCheckRole("root")
  @Operation(summary = "菜单树")
  @PostMapping("/getMenuTree")
  @SaIgnore
  public List<MenuVO> getMenuTree(@RequestBody MenuQueryDTO queryDTO) {
    List<Menu> menuList = menuService.list();
    if (CommonUtil.isNullOrEmpty(menuList)) {
      return null;
    }

    return menuService.getMenuList(null, queryDTO);
  }

  @SaCheckRole("root")
  @Operation(summary = "权限分配")
  @PostMapping("/permissionAssignment")
  public void permissionAssignment(@RequestBody @Valid PermissionAssignmentDTO permissionAssignmentDTO) {
    menuService.permissionAssignment(permissionAssignmentDTO);
  }

  @SaCheckRole("root")
  @Operation(summary = "根据角色id获取权限列表")
  @PostMapping("/getPermissionList")
  public List<String> getPermissionList(@RequestBody @Valid IdParamDTO idParamDTO) {
    return menuService.getPermissionList(idParamDTO.getId());
  }
}
